package fr.inria.zvtm.engine;

import java.awt.Color;
import java.awt.Image;

import jpavlich.cardsorter.action.Action;
import jpavlich.cardsorter.action.Experiment;
import fr.inria.zvtm.glyphs.Composite;
import fr.inria.zvtm.glyphs.Glyph;
import fr.inria.zvtm.glyphs.VImage;
import fr.inria.zvtm.glyphs.VText;

public class Button extends Composite implements ActionListener {

	private Action<?>[] actions;
	private Experiment mgr;
	private Image[] images;
	private VImage vImage;
	protected int current = 0;

	public Button(double x, double y, int z, Action<?> action, Experiment mgr, String text, Image img) {
		this(x,y,z,new Action[]{action}, mgr,text,new Image[]{img});
	}
	
	/**
	 * @param x
	 * @param y
	 * @param z
	 * @param actions Array of actions that the button can perform. The action to execute is changed by calling {@link #setCurrentAction(int)}
	 * @param mgr
	 * @param text
	 * @param img Array of images. This array must match the actions array, i.e., both must have the same size, and image positions must correspond to the action
	 */
	public Button(double x, double y, int z, Action<?>[] actions, Experiment mgr, String text, Image[] img) {
		super();

		this.actions = actions;
		this.mgr = mgr;
		this.images = img;
		vImage = null;
		if (img != null && img.length > 0) {
			vImage = new VImageWithListener(x, y, z, img[0]) {

				@Override
				public void actionPerformed() {
					Button.this.actionPerformed();
				}
			};
			vImage.setBorderColor(new Color(0, 0, 0, 1));
			addChild(vImage);
//			vs.addGlyph(vImage);
		}
		if (text != null && !text.isEmpty()) {
			VText t = new VTextWithListener(x, y, z, Color.BLACK, text) {
				@Override
				public void actionPerformed() {
					Button.this.actionPerformed();
				}
			};
			t.setTextAnchor(VText.TEXT_ANCHOR_MIDDLE);
			t.setScale(3);
			if (vImage != null) {
				t.moveTo(x, vImage.vy - vImage.vh / 2 + t.getFont().getSize2D() * t.getScale() / 2);
			}
			addChild(t);
//			vs.addGlyph(t);
		}
	}

	@Override
	public void actionPerformed() {
		mgr.execute(actions[current], true);
	}

	public double getWidth() {
		double[] bounds = getBounds();
		return bounds[2] - bounds[0];
	}

	public double getHeight() {
		double[] bounds = getBounds();
		return bounds[1] - bounds[3];
	}

	@Override
	public short mouseInOut(int jpx, int jpy, int camIndex, double cvx, double cvy) {
		short response = NO_CURSOR_EVENT;
		for (Glyph g : this.peekAtChildren()) {
			response = g.mouseInOut(jpx, jpy, camIndex, cvx, cvy);
			if (response != NO_CURSOR_EVENT) {
				return response;
			}
		}
		return response;
	}
	
	public void setCurrentAction(int i) {
		if (images != null && i < images.length && actions!= null && i < actions.length) {
			current = i;
			vImage.setImage(images[i]);
		}
	}

	@Override
	public void resetMouseIn() {
		for (Glyph g : peekAtChildren()) {
			g.resetMouseIn();
		}
	}
	
	

}
